<template>
  <div class="view-fill">
    <div
      v-if="!modifyInfo.visible && !assetApplicationDetailInfo.visible"
      class="app-container-flex"
    >
      <NewFullScreen
        v-model="showDialog"
        title="合同详情"
        :needOperateAffair="true"
        :operateAffairData="affairTableInfo"
        @returnBack="returnBack"
      >
        <template v-slot:full-button>
          <PopoverPrint
            ref="popoverShow"
            v-model:popoverVisible="popoverVisible"
            :canPrint="
              $permission('contract:printOrderDetail') &&
              infoList.data.status !== 1
            "
            :templateArr="templateArr"
            @tempClick="tempClick"
            @print="print"
          ></PopoverPrint>
          <!--  <el-button
            v-if="
              $permission('contract:printOrderDetail') &&
              infoList.data.status !== 1
            "
            @click="print"
            >打印</el-button
          > -->
          <el-button
            v-if="
              $permission('contract:download') && infoList.data.status !== 1
            "
            @click="exportExcel"
            >导出excel</el-button
          >
          <el-button v-if="canUpdate" @click="update">修改</el-button>
          <el-button v-if="canSubmit" @click="submit">提交</el-button>
          <el-button v-if="canCheck" @click="check">审核</el-button>
          <el-button v-if="canReject" @click="reject">驳回</el-button>
          <el-button v-if="canRevoke" @click="revoke">撤回</el-button>
          <el-button v-if="canEnable" @click="enable">启用</el-button>
          <el-button v-if="canDisable" @click="enable">停用</el-button>
          <el-button v-if="canPrint" @click="print">打印</el-button>
          <el-button v-if="canExcel" @click="exportExcel">导出excel</el-button>
        </template>
        <div class="model-panel">
          <div class="model-panel-title">
            <p>{{ $t('basic_information') }}</p>
          </div>
          <div class="model-panel-body">
            <basic-information :info="infoList"> </basic-information>
          </div>
        </div>
        <div v-show="infoList.data.contractType == '1'" class="model-panel">
          <div class="model-panel-title">
            <p>维保信息</p>
          </div>
          <div class="model-panel-body">
            <basic-information :info="maintenanceInfoList"> </basic-information>
          </div>
        </div>
        <div class="model-panel">
          <div class="model-panel-title">
            <p>招标信息</p>
          </div>
          <div class="model-panel-body">
            <basic-information :info="biddingInfoList"> </basic-information>
          </div>
        </div>
        <div class="model-panel">
          <div class="model-panel-title">
            <Tooltip :text="'付款信息'"></Tooltip>
          </div>
          <div class="model-panel-body">
            <div class="flex_full_item">
              <!-- 表格 -->
              <page-table
                :refresh="payDetailInfo.refresh"
                :init-curpage="payDetailInfo.initCurpage"
                v-model:data="payDetailInfo.data"
                :pager="false"
                :check-box="false"
                :tab-index="true"
                :field-list="payDetailInfo.fieldList"
              >
              </page-table>
            </div>
          </div>
        </div>
        <div v-show="infoList.data.contractType == '1'" class="model-panel">
          <div class="model-panel-title">
            <Tooltip :text="'验收标准'"></Tooltip>
          </div>
          <div class="model-panel-body">
            <div class="flex_full_item">
              <!-- 表格 -->
              <page-table
                :refresh="acceptanceInfo.refresh"
                :init-curpage="acceptanceInfo.initCurpage"
                v-model:data="acceptanceInfo.data"
                :pager="false"
                :check-box="false"
                :tab-index="true"
                :field-list="acceptanceInfo.fieldList"
              >
              </page-table>
            </div>
          </div>
        </div>
        <div v-if="infoList.data.contractType == '1'" class="model-panel">
          <div class="model-panel-title">
            <Tooltip :text="$t('detailInfo')"></Tooltip>
          </div>
          <div class="model-panel-body">
            <div class="flex_full_item">
              <!-- 表格 -->
              <page-table
                :refresh="tableInfo.refresh"
                :init-curpage="tableInfo.initCurpage"
                v-model:data="tableInfo.data"
                :pager="false"
                :check-box="false"
                :tab-index="true"
                :field-list="tableInfo.fieldList"
              >
                <template v-slot:col-assetApplicationNo="scope">
                  <span
                    class="slip-edit"
                    @click="
                      showAssetApplicationDetail(scope.row.assetApplicationId)
                    "
                    >{{ scope.row.assetApplicationNo }}</span
                  >
                </template>
              </page-table>
            </div>
          </div>
        </div>

        <div v-else class="model-panel">
          <div class="model-panel-title">
            <Tooltip :text="$t('detailInfo')"></Tooltip>
          </div>
          <div class="model-panel-body">
            <div class="flex_full_item">
              <!-- 表格 -->
              <page-table
                :refresh="productTableInfo.refresh"
                :init-curpage="productTableInfo.initCurpage"
                v-model:data="productTableInfo.data"
                :pager="false"
                :check-box="false"
                :tab-index="true"
                :field-list="productTableInfo.fieldList"
              >
              </page-table>
            </div>
          </div>
        </div>

        <div class="model-panel">
          <div class="model-panel-title">
            <p>附件信息</p>
          </div>
          <div class="model-panel-body">
            <basic-information :info="fileUrlListInfoList">
              <template v-slot:basic-filePathList>
                <EleGallery
                  v-if="
                    fileUrlListInfoList.data.filePathList &&
                    fileUrlListInfoList.data.filePathList.length
                  "
                  :lazy="true"
                  :size="150"
                  :source="fileUrlListInfoList.data.filePathList"
                  title="合同附件"
                />
                <span v-else>-</span>
              </template>
            </basic-information>
          </div>
        </div>
      </NewFullScreen>
    </div>
    <order-modify
      v-if="modifyInfo.visible"
      :id="modifyInfo.id"
      v-model:visible="modifyInfo.visible"
      :title="modifyInfo.title"
      @returnModify="returnModify"
    />
    <assetApplicationDetails
      v-if="assetApplicationDetailInfo.visible"
      :id="assetApplicationDetailInfo.id"
      v-model:visible="assetApplicationDetailInfo.visible"
      :title="assetApplicationDetailInfo.title"
    />
    <asset-card-detail
      v-if="assetDetailInfo.visible"
      :id="assetDetailInfo.id"
      v-model:visible="assetDetailInfo.visible"
      :title="assetDetailInfo.title"
    />
  </div>
</template>

<script setup>
import {
  changeStatusContract,
  getContractDetailCustomizeListAll,
  selectContractById,
  getContractPayDetailByOrderId,
  getContractAcceptanceDetailByOrderId,
  submitContract,
  checkContract,
  rejectContract,
  revokeContract,
  exportContractDetail,
  printContractDetail,
  getContractProductDetailCustomizeListAll,
} from '@/api/contract.js'
import { getCustomizeSetting } from '@/api/customize'
import { orderOpAffairAll } from '@/api/affair'
import { fatchTemplateByCode } from '@/api/base'
import EleGallery from '@/components/UploadImgNew/eleGallery'
import { doPrint } from '@/utils/exportUtil.js'
import { selectByCodeAndDept } from '@/api/report.js'
import { updatePrintCount } from '@/api/mapping'

const OrderModify = defineAsyncComponent(() => import('./modify'))
const assetApplicationDetails = defineAsyncComponent(() =>
  import('@/views/asset/assetManage/assetApplication/details')
)
const AssetCardDetail = defineAsyncComponent(() =>
  import('@/views/asset/assetManage/assetCard/details')
)

const emits = defineEmits()
const { proxy } = getCurrentInstance()
const props = defineProps(['visible', 'id'])

const infoList = ref({
  data: {},
  fieldList: [
    { label: '合同编号', value: 'orderNo', type: 'text' },
    { label: '合同名称', value: 'contractName', type: 'text' },
    { label: '合同类型', value: 'contractTypeValue', type: 'text' },
    { label: '业务类型', value: 'businessTypeValue', type: 'text' },
    { label: '签订部门', value: 'signDeptName', type: 'text' },
    { label: '公司名称', value: 'company', type: 'text' },
    { label: '开票方式', value: 'invoiceTypeValue', type: 'text' },
    { label: '金额', value: 'amount', type: 'text' },
    { label: '签订人', value: 'signUserName', type: 'text' },
    { label: '供应商', value: 'supplierName', type: 'text' },
    { label: '签订日期', value: 'signDate', type: 'text' },
    { label: '联系电话', value: 'contactTel', type: 'text' },
    { label: '资产归口部门', value: 'assetBelongDeptName', type: 'text' },
    { label: '验收日期', value: 'acceptanceDate', type: 'text' },
    { label: '要求到货日期', value: 'arrivalDate', type: 'text' },
    { label: '合同开始日期', value: 'contractStartDate', type: 'text' },
    { label: '合同结束日期', value: 'contractEndDate', type: 'text' },
    { label: '状态', value: 'statusValue', type: 'text' },
    { label: '停启用状态', value: 'isEnableValue', type: 'text' },
    {
      label: '总金额限制',
      value: 'sumAmountLimitValue',
      type: 'text',
    },
    {
      label: '产品数量限制',
      value: 'qtyLimitValue',
      type: 'text',
    },
    { label: '备注', value: 'remark', type: 'popover' },
  ],
})
const maintenanceInfoList = ref({
  data: {},
  fieldList: [
    { label: '维修保养(年)', value: 'maintenanceYears', type: 'text' },
    {
      label: '维修开始日期',
      value: 'maintenanceStartDate',
      type: 'text',
    },
    { label: '维修结束日期', value: 'maintenanceEndDate', type: 'text' },
  ],
})
const fileUrlListInfoList = ref({
  data: {},
  fieldList: [{ label: '合同附件', value: 'filePathList', type: 'slot' }],
})
const biddingInfoList = ref({
  data: {},
  fieldList: [
    { label: '招标日期', value: 'biddingDate', type: 'text' },
    { label: '招标文件编号', value: 'biddingFileNo', type: 'text' },
    { label: '招标方式', value: 'biddingTypeValue', type: 'text' },
    { label: '中标日期', value: 'winBiddingDate', type: 'text' },
    { label: '中标文件编号', value: 'winBiddingFileNo', type: 'text' },
    {
      label: '中标供应商',
      value: 'winBiddingSupplierName',
      type: 'text',
    },
  ],
})
const payDetailInfo = ref({
  data: [],
  fieldList: [
    { label: '付款期', value: 'payPeriod' },
    { label: '付款比例(%)', value: 'payRate' },
    { label: '金额', value: 'payAmount' },
    { label: '付款类型', value: 'payTypeValue' },
    { label: '付款条件', value: 'payConditionValue' },
    { label: '付款日期', value: 'payDate' },
    { label: '付款状态', value: 'payStatusValue' },
    { label: '支付方式', value: 'payWayValue' },
    { label: '备注', value: 'operateTypeValue' },
  ],
})
const acceptanceInfo = ref({
  data: [],
  fieldList: [
    { label: '验收项目', value: 'acceptanceItem' },
    { label: '验收标准/要求', value: 'acceptanceCriterion' },
    { label: '备注', value: 'remark' },
  ],
})
// 过滤相关配置
const filterInfo = ref({
  query: {
    customizeUserVO: {},
    queryMap: {
      orderId: {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: props.id,
      },
    },
    queryParams: {
      needPendContractQty: 1,
    },
  },
})
// 过滤相关配置
const productFilterInfo = ref({
  query: {
    customizeUserVO: {},
    queryMap: {
      orderId: {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: props.id,
      },
    },
    queryParams: {},
  },
})
const modifyInfo = ref({
  id: '',
  visible: false,
  title: '',
})
const assetApplicationDetailInfo = ref({
  id: '',
  visible: false,
  title: '资产申购论证详情',
})
// 表格相关
const tableInfo = ref({
  refresh: 1,
  initCurpage: 1,
  data: [],
  fieldList: [],
})
// 表格相关
const productTableInfo = ref({
  refresh: 1,
  initCurpage: 1,
  data: [],
  fieldList: [],
})
const assetDetailInfo = ref({
  visible: false,
  id: '',
  title: '资产详情',
})
const purchDetailInfo = ref({
  visible: false,
  orderId: '',
})
const affairTableInfo = ref({
  api: orderOpAffairAll,
  query: {
    orderType: 61,
    orderId: props.id,
    sort: 'operate_time desc',
  },
})

const showDialog = computed({
  get() {
    return props.visible
  },
  set(newValue) {
    emits('update:visible', newValue) // 更新父组件visible
  },
})
const canUpdate = computed(() => {
  return (
    proxy.$permission('contract:update') && infoList.value.data.status === 1
  )
})
const canSubmit = computed(() => {
  return (
    proxy.$permission('contract:submit') && infoList.value.data.status === 1
  )
})
const canReject = computed(() => {
  return (
    proxy.$permission('contract:reject') && infoList.value.data.status === 2
  )
})
const canRevoke = computed(() => {
  return (
    proxy.$permission('contract:revoke') && infoList.value.data.status === 2
  )
})
const canCheck = computed(() => {
  return proxy.$permission('contract:check') && infoList.value.data.status === 2
})
const canPrint = computed(() => {
  return (
    proxy.$permission('contract:printDetail') &&
    infoList.value.data.status !== 1 &&
    infoList.value.data.status !== 2
  )
})
const canExcel = computed(() => {
  return (
    proxy.$permission('contract:excelDetail') &&
    infoList.value.data.status !== 1 &&
    infoList.value.data.status !== 2
  )
})
const canEnable = computed(() => {
  return (
    proxy.$permission('contract:enable') &&
    infoList.value.data.isEnable === 0 &&
    infoList.value.data.status === 4
  )
})
const canDisable = computed(() => {
  return (
    proxy.$permission('contract:disable') &&
    infoList.value.data.isEnable === 1 &&
    infoList.value.data.status === 4
  )
})

watch(
  () => props.visible,
  (value) => {
    showDialog.value = value
  },
  {
    immediate: true,
  }
)
watch(
  () => props.id,
  (newVal) => {
    filterInfo.value.query.queryMap.orderId.value = newVal
    productFilterInfo.value.query.queryMap.orderId.value = newVal
    affairTableInfo.value.query.orderId = newVal
    getCustomize()
  },
  {
    immediate: true,
    deep: true,
  }
)

setData()
function setData() {
  tableInfo.value.fieldList = Object.values({
    ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
    assetApplicationNo: {
      label: '资产申购论证单号',
      value: 'assetApplicationNo',
      type: 'slot',
      show: false,
      hidden: true,
    },
  })
  productTableInfo.value.fieldList = Object.values({
    ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
  })
  getCustomize()
}
function enable() {
  //停启用
  let params = {
    id: infoList.value.data.id,
    isEnable: infoList.value.data.isEnable ? 0 : 1,
  }
  changeStatusContract(params).then((res) => {
    if (res && res.success) {
      getMain()
    }
  })
}
function showAssetDetail(row) {
  assetDetailInfo.value.id = row.assetId
  assetDetailInfo.value.visible = true
}
function showAssetApplicationDetail(id) {
  assetApplicationDetailInfo.value.id = id
  assetApplicationDetailInfo.value.visible = true
}
//提交
function submit() {
  submitContract([props.id]).then((resp) => {
    if (resp && resp.success) {
      getMain()
    }
  })
}
//驳回
function reject() {
  rejectContract([props.id]).then((resp) => {
    if (resp && resp.success) {
      getMain()
    }
  })
}
//审核
function check() {
  checkContract([props.id]).then((resp) => {
    if (resp && resp.success) {
      getMain()
    }
  })
}
//撤回
function revoke() {
  revokeContract([props.id]).then((resp) => {
    if (resp && resp.success) {
      getMain()
    }
  })
}
function returnBack() {
  emits('returnBack', false)
}
function returnModify() {
  getMain()
}
function showFieldListItem(show, nameValue) {
  let fieldList = infoList.value.fieldList
  fieldList.map((item) => {
    if (item.value === nameValue) {
      item.show = show
    }
  })
}
function getMain() {
  selectContractById(props.id).then((resp) => {
    if (resp && resp.success) {
      infoList.value.data = resp.data
      maintenanceInfoList.value.data = resp.data
      biddingInfoList.value.data = resp.data
      fileUrlListInfoList.value['data'] = resp.data
      if (Number(infoList.value.data.contractType) === 2) {
        showFieldListItem(false, 'acceptanceDate')
        showFieldListItem(false, 'arrivalDate')
        showFieldListItem(true, 'sumAmountLimitValue')
        showFieldListItem(true, 'qtyLimitValue')
        showFieldListItem(false, 'businessTypeValue')
      } else {
        showFieldListItem(true, 'acceptanceDate')
        showFieldListItem(true, 'arrivalDate')
        showFieldListItem(false, 'sumAmountLimitValue')
        showFieldListItem(false, 'qtyLimitValue')
      }
      getList()
    }
  })
}
function getList() {
  let params = {
    orderId: props.id,
  }
  if (Number(infoList.value.data.contractType) === 1) {
    showFieldListItem(true, 'businessType')
    showFieldListItem(true, 'assetBelongDeptName')
    getContractDetailCustomizeListAll(filterInfo.value.query).then((resp) => {
      if (resp && resp.success) {
        tableInfo.value.data = resp.data
      }
    })
    getContractAcceptanceDetailByOrderId(params).then((resp) => {
      if (resp && resp.success) {
        acceptanceInfo.value.data = resp.data
      }
    })
  } else {
    showFieldListItem(false, 'businessType')
    showFieldListItem(false, 'assetBelongDeptName')
    getContractProductDetailCustomizeListAll(
      productFilterInfo.value.query
    ).then((res) => {
      if (res && res.success) {
        productTableInfo.value.data = res.data
      }
    })
  }
  getContractPayDetailByOrderId(params).then((resp) => {
    if (resp && resp.success) {
      payDetailInfo.value.data = resp.data
    }
  })
}
function update() {
  modifyInfo.value.id = props.id
  modifyInfo.value.title = '修改'
  modifyInfo.value.visible = true
}
function exportExcel() {
  let query = ''
  if (infoList.value.data.contractType == '1') {
    query = filterInfo.value.query
  } else if (infoList.value.data.contractType == '2') {
    query = productFilterInfo.value.query
  }

  exportContractDetail(query).then((resp) => {
    if (resp) {
      proxy.$fn.parseExcel(resp)
    }
  })
}
const templateArr = ref([])
const popoverVisible = ref(false)
function print() {
  // contractType: 2 contractTypeValue: "耗材合同"
  // contractType: 1 contractTypeValue: "资产合同"
  selectByCodeAndDept({
    tempCode:
      infoList.value.data.contractType == 2
        ? 'productContractDetail'
        : 'assetContractDetail',
    deptId: infoList.value.data.deptId,
  }).then((res) => {
    if (res && res.success) {
      templateArr.value = res.data
      popoverVisible.value = true
      // 一条数据则直接打印
      if (templateArr.value.length === 1) {
        proxy.$refs.popoverShow.hidePopover()
        doPrint({
          name: templateArr.value[0].ureportName,
          params: {
            orderId: infoList.value.data.id,
          },
          callback: printCallback,
          data: {},
        })
      }
    }
  })
  /* let printCode =
    infoList.value.data.contractType == '1'
      ? 'contract:printDetail'
      : 'contract:printProductDetail'
  fatchTemplateByCode({
    resourceCode: printCode,
    isDefault: 1,
  }).then((res) => {
    if (res && res.success) {
      let temp = proxy.$fn.getPrintTemp(res.data[0])
      getPrintData(temp)
    }
  }) */
}
function printCallback() {
  try {
    // 打印成功增加打印次数
    updatePrintCount({
      orderNo: infoList.value.data.orderNo,
      orderId: props.id,
      orderType: 61,
    })
  } catch (error) {}
}
function tempClick(item) {
  doPrint({
    name: item.ureportName,
    params: {
      orderId: infoList.value.data.id,
    },
    callback: printCallback,
    data: {},
  })
  popoverVisible.value = false
}
function getPrintData(temp) {
  let params = {
    customizeDto:
      infoList.value.data.contractType == '1'
        ? filterInfo.value.query
        : productFilterInfo.value.query,
    orderIds: [props.id],
  }
  printContractDetail(params).then((res) => {
    if (res.success && res) {
      let data = proxy.$fn.deepClone(res.data)
      let newData = data.map((item) => {
        return {
          ...item,
          ...item.orderInfo,
        }
      })
      proxy.$lodop.preview(temp, newData)
    }
  })
}
function getCustomize() {
  let _tableInfo = tableInfo.value
  let param = {
    tableKey:
      'contractDeviceDetail-com.slip.spd.entity.vo.contract.ContractDetailVO',
  }
  getCustomizeSetting(param).then((res) => {
    if (res && res.success) {
      let data = res.data
      filterInfo.value.query.customizeUserVO = data
      let obj = proxy.$fn.setFieldList(_tableInfo.fieldList, data.detail, true)
      _tableInfo.fieldList = obj.fieldList
      let productParam = {
        tableKey:
          'contractProductDetail-com.slip.spd.entity.vo.contract.ContractProductDetailVO',
      }
      getCustomizeSetting(productParam).then((res) => {
        if (res && res.success) {
          let data = res.data
          productFilterInfo.value.query.customizeUserVO = data
          let productObj = proxy.$fn.setFieldList(
            productTableInfo.value.fieldList,
            data.detail,
            true
          )
          productTableInfo.value.fieldList = productObj.fieldList
        }
        getMain()
      })
    }
  })
}
</script>

<style scoped></style>
